/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>

*/
package cmd

import (
	"mysqlAdmin/lib/log"
	"mysqlAdmin/lib/serviceAdmin"

	"github.com/spf13/cobra"
)

// serviceCmd represents the service command
var serviceCmd = &cobra.Command{
	Use:   "service",
	Short: "服务管理",
	Long:  `服务管理`,
	Run: func(cmd *cobra.Command, args []string) {
		run()
	},
}
var serviceAction string

func init() {
	rootCmd.AddCommand(serviceCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// serviceCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// serviceCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")

	serviceCmd.Flags().StringVarP(&serviceAction, "action", "a", "list", "mysql服务管理")
	// serviceCmd.Flags().StringVarP(&serviceAction, "action", "a", "list", "用户操作")
}

func run() {
	initConfig()
}

func initConfig() {

	config, err := serviceAdmin.ReadConfigurations()
	if err != nil {
		log.Error("无法初始化配置文件")
	}

	log.Infof("当前服务配置数量:%d", len(config.Services))

	log.Infof("执行动作:%s", serviceAction)

	if serviceAction == "list" {
		listService(*config)
	}
	if serviceAction == "add" {
		addService(*config)
	}
}

func listService(config serviceAdmin.Configurations) {

	for i, service := range config.Services {
		log.Infof("ID:%d", i)
		log.Infof("端口:%d", service.Port)
		log.Infof("路径:%d", service.Path)
	}
}

func addService(config serviceAdmin.Configurations) {

	port := 3306 + len(config.Services)
	log.Infof("增加服务,端口:%d", port)

	config.AddService(port)

}
